// 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。

// 输入：head = [1, 2, 3, 4, 5], k = 2
// 输出：[4, 5, 1, 2, 3]

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function (head, k) {
    if (head === null || k === 0)
        return head
    let len = 0;
    let p = head, pre = head; // pre是尾结点
    while (p) {
        pre = p;
        p = p.next;
        len++;
    }
    k = k % len; // 更新k的值

    if (k === 0)
        return head;

    p = head;
    let next = p;
    for (let i = 0; i < len - k; i++) { // 将前面的len - k个结点移到后面
        next = p.next;
        p.next = null;
        pre.next = p;
        pre = p;
        p = next;
    }
    return next;
};